﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.Domain.专检;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.AbnormalCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.AbnormalHandler
{
    public class AddAbnormalHandler : IRequestHandler<AddAbnormalCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public AddAbnormalHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<object>> Handle(AddAbnormalCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var model = mapper.Map<Abnormal>(request);
            // 生成 4 位随机数字
            Random random = new Random();
            string yeartime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string randomDigits = random.Next(1000, 9999).ToString();
            string ProductCodess1 = "YCCL" + randomDigits + yeartime;
            string ProductCodess2 = randomDigits + yeartime;
            model.ExceptionNumber = ProductCodess1;
            model.IsDel = false;
            result.data = await db.Insertable(model).ExecuteCommandAsync();
            if ((int)result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "异常处理添加成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "异常处理表添加失败";
            }
            return result;
        }
    }
}
